<template>
    <div class="bigbox">
        <div>
            <h1>添加或修改</h1>
        </div>
        <div>
            <table>
                <tbody>
                    <tr>
                        <td>商品名称：<input type="text" placeholder="请输入商品名称" v-model="data.formProtect.protectName"></td>
                        <td>商品价格：<input type="text" placeholder="请输入商品名称" v-model="data.formProtect.protectPrice"></td>
                        <td>商品数量：<input type="text" placeholder="请输入商品名称" v-model="data.formProtect.protectNum"></td>
                    </tr>
                    <tr>
                        <td>
                            <input type="button" value="确认" @click="saveBtn">
                            <input type="button" value="返回" @click="cancelBtn">
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const api = "http://localhost:3000"

const router = useRouter()

const id = useRoute().params.id

const data = reactive({
    formProtect: {}
})

//新增或修改商品
function saveBtn() {
    if (id) {
        axios.put(`${api}/protect/${id}`, data.formProtect).then(() => {
            router.push({ name: 'protect' })
        })
    } else {
        axios.post(`${api}/protect`, data.formProtect).then(() => {
            router.push({ name: 'protect' })
        })
    }
}
//根据id查询商品信息
function queryById() {
    axios.get(`${api}/protect/${id}`).then((res) => {
        data.formProtect = res.data.data
    })
}
//取消操作
function cancelBtn() {
    router.push({ name: 'protect' })
}
//组件挂载时执行
onMounted(() => {
    console.log(id);
    if (id) {
        queryById()
    }
})
</script>
 <style scoped>
  /* 这里可以添加样式 */
  .bigbox {
    font-family: Arial, sans-serif;
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  
  h1 {
    text-align: center;
  }
  
  table {
    width: 100%;
    margin-top: 20px;
  }
  
  td {
    padding: 10px;
  }
  
  input[type="text"] {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  
  input[type="button"] {
    padding: 10px 20px;
    margin-right: 10px;
    border: none;
    border-radius: 4px;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
  }
  
  input[type="button"]:hover {
    background-color: #45a049;
  }
  </style>
  